package net.tbao.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.tbao.common.exception.NoStockException;
import net.tbao.common.to.mq.OrderTo;
import net.tbao.common.to.mq.StockDetailTo;
import net.tbao.common.to.mq.StockLockedTo;
import net.tbao.common.utils.R;
import net.tbao.ware.entity.WareOrderTaskDetailEntity;
import net.tbao.ware.entity.WareOrderTaskEntity;
import net.tbao.ware.feign.OrderFeignService;
import net.tbao.ware.feign.ProductFeignService;
import net.tbao.ware.service.WareOrderTaskDetailService;
import net.tbao.ware.service.WareOrderTaskService;
import net.tbao.ware.vo.*;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.tbao.common.utils.PageUtils;
import net.tbao.common.utils.Query;

import net.tbao.ware.dao.WareSkuDao;
import net.tbao.ware.entity.WareSkuEntity;
import net.tbao.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

@RabbitListener(queues = "stock.release.stock.queue")
@Service("wareSkuService")
@Slf4j
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareOrderTaskDetailService  wareOrderTaskDetailService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderFeignService orderFeignService;

    @RabbitHandler
    public void handleStockLockRelease(StockLockedTo to,Message message,Channel channel) throws IOException {

    }



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
//1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(entities == null || entities.size() == 0){
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);

            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                if(info.getCode() == 0){
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }


            wareSkuDao.insert(skuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    /**
     * 查询SKU 库存信息
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {

            SkuHasStockVo vo = new SkuHasStockVo();

            Long count = baseMapper.getSkuStock(skuId);

            vo.setSkuId(skuId);
            vo.setHasStock(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }


    /**
     * 解锁库存
     *
     * @param skuId        商品skuId
     * @param wareId       仓库id
     * @param count        需要解锁的数量
     * @param taskDetailId 库存工作单id
     */
    public void unLockStock(Long skuId, Long wareId, Integer count, Long taskDetailId) {
        // 1、解锁库存
        baseMapper.unLockStock(skuId, wareId, count);
        // 2、更新库存工作单的状态
        WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity();
        taskDetailEntity.setId(taskDetailId);
        taskDetailEntity.setLockStatus(2); // 已解锁
        wareOrderTaskDetailService.updateById(taskDetailEntity);
    }


    /**
     * 为某个订单锁定库存
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        //保存库存工作单
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
          List<Long> wareId= wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareId);
            return stock;
        }).collect(Collectors.toList());
        //锁定库存
        Boolean allLock=true;
        for (SkuWareHasStock stock : collect) {
            Boolean skuStock=false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            if(wareIds==null||wareIds.size()==0){
                //没有仓库有商品
                throw new NoStockException(skuId);
            }
            for (Long wareId :wareIds){

                //成功返回1 否则就是0
                Long conu=wareSkuDao.lockSkuStock(skuId,wareId,stock.getNum());
                if (conu==1){
                    skuStock=true;

                    //保存工作单
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity
                            (null,skuId,"",stock.getNum(),taskEntity.getId(),wareId,1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                    // TODO 告诉MQ 库存锁定成功

                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockDetailTo);
                    stockLockedTo.setStockDetail(stockDetailTo);

                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;

                }else {
                    //当前仓库锁定失败，重试下个仓库
                }
            }
            if (skuStock==false){
                //当前商品所有仓库没有锁住
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    /**
     * 构建解锁库存内容
     * @param to
     */
    @Override
    public void buidUnlockStock(StockLockedTo to) {
        System.out.println("收到库存解锁消息");
        StockDetailTo detail = to.getStockDetail();
        Long detailId = detail.getId();
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if(byId!=null){
            //解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if(r==null || r.getCode()==0){
                OrderVo data = r.getData(new TypeReference<OrderVo>() {});
                if(data.getStatus()==4){
                    unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                }
            }else {
                //消息拒绝，重新放回队列
                throw new RuntimeException("远程服务");

            }

        }else {
            //不用解锁

        }
    }

    /**
     * 订单关闭解锁库存
     * @param orderTo
     */
    @Transactional
    @Override
    public void buidUnlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        // 根据订单号查询库存工作单信息
        WareOrderTaskEntity taskEntity = wareOrderTaskService.getByOrderSn(orderSn);
        Long taskEntityId = taskEntity.getId();
        // 按照工作单的id查询未解锁的库存
        List<WareOrderTaskDetailEntity> orderTaskDetailEntityList = wareOrderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>()
                        .eq("task_id", taskEntityId)
                        .eq("lock_status", 1));

        for (WareOrderTaskDetailEntity entity : orderTaskDetailEntityList) {
            // 依次遍历解锁
            unLockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }
    }


    @Data
    class  SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}

